// pages/HomePage/HomePage.js
var api = require("../../utils/request.js");
var screenUtil = require("../../utils/screen.js");
const ballFallAnimation = require("../../utils/ballFallAnimation.js");
var clickThrottle = require("../../utils/clickThrottle.js");
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showGuige: false,
    showGuige2: false,
    hideUplooadModal: true,
    hideModal: true, //模态框的状态 true-隐藏 false-显示
    animationData: {}, //
    targetData: {},
    totalProductNum: 0,
    selectedProducts: [],
    selectIndexs: [],
    modifyProducts: [],
    isModify: false,
    isTriggered: false,

    commodityList: [],
    ballAnimationArray: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], //小球动画
    keyFrames: [], //动画帧
    bus_y: -20, //手指点击的位置
    finishShopCarAnimation: true, //购物车动画是否结束
    tuangouID: '',
    userNickname: '',
    avatarUrl: defaultAvatarUrl,
    isUploadAvatar: false,
    isClickImage: false,
    lastSpecsNum: 0, //记录点开上次多规格商品数量
    showTuanwuche: false,
    lastExistNum: false,
    comeInCorrectScene: true,
    isPartModify: false,
    proDetailIndex: 0,
    showProDetail: false,
    hasOrderedProduct: false,
    hasBenQiOrder: false,
    showModeOrder: false,
    buyProAgain: false,
    otherTuangou: false,
    leaderID: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.tuangouID = options.id
    this.data.leaderID = options.userId
    this.data.buyProAgain = options.buyProAgain;
    this.data.otherTuangou = options.otherTuangou;
    if (options.otherTuangou == undefined) {
      this.data.otherTuangou = false
    }
    console.log('cccrrc=' + this.data.otherTuangou)
    if (options.buyProAgain == undefined) {
      this.data.buyProAgain = false
    }
    console.log('ccccc=' + this.data.buyProAgain)
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
    var screen = screenUtil.screenUtil()
    var bottomHeight = 120
    var scrHeight = screen.windowHeight
    // 设置购物车位置
    this.busPos = {};
    this.busPos["x"] = 45; // 购物车的位置
    this.busPos["y"] = wx.getSystemInfoSync().windowHeight - 56;

    // //console.log("getApp().globalData.windowHeight",getApp().globalData.windowHeight)
    // //console.log("getApp().globalData.statusBarHeight",getApp().globalData.statusBarHeight)
    // //console.log("getApp().globalData.naviBarHeight",getApp().globalData.naviBarHeight)
    // //console.log("getApp().globalData.zHeight",getApp().globalData.zHeight)
    var app = getApp();
    if (app.globalData.checkLogin == true) {
      console.log("更多团购进来的")
      this.getTargetDetail(this.data.tuangouID);

      this.setData({
        screenheight: scrHeight,
        isIphoneX: getApp().globalData.statusBarHeight >= 44 ? true : false,
        btmHeight: bottomHeight,
        scrWidth: screen.windowWidth,
        pageHeight: getApp().globalData.windowHeight,
        zHeight: getApp().globalData.zHeight * 2,
        statusBarHeight: getApp().globalData.statusBarHeight,
      })
    } else {
      app.checkLoginReadyCallback = res => {
        //登陆成功后自己希望执行的，和上面一样
        this.data.tuangouID = '1470'
        this.getTargetDetail(this.data.tuangouID);
        //console.log('zHeight==',getApp().globalData.zHeight*2);
        this.setData({
          screenheight: scrHeight,
          isIphoneX: getApp().globalData.statusBarHeight >= 44 ? true : false,
          btmHeight: bottomHeight,
          scrWidth: screen.windowWidth,
          pageHeight: getApp().globalData.windowHeight,
          zHeight: getApp().globalData.zHeight * 2,
          statusBarHeight: getApp().globalData.statusBarHeight,
        })
      };

    }
  },

  //判断是否是iphoneX
  isIphoneX() {
    let mobile = wx.getSystemInfoSync();
    if (mobile.model.indexOf("iPhone X") >= 0) {
      return true;
    } else {
      return false;
    }
  },

  swiperChange: function (event) {
    var that = this
    //console.log("swiperChange", event);
    var current = event.detail.current;
    var currID = event.currentTarget.dataset.id;
    this.setData({
      currentIndex: event.detail.current,
      currentID: currID,
      [that.data.targetData.productList[currID].scroll]: 1
    })
  },
  swiperChange2: function (event) {
    //console.log("swiperChange", event);
    var current = event.detail.current;
    var currID = event.currentTarget.dataset.id;
    this.setData({
      currentIndex2: event.detail.current
    })
  },
  getName(e) {
    this.data.userNickname = e.detail.value;
  },
  submit: function () {
    var that = this
    if (that.data.isUploadAvatar == false) {
      wx.showToast({
        title: '请设置头像',
        icon: "error"
      })
      return
    }

    if (that.data.userNickname.length == 0) {
      wx.showToast({
        title: '请输入昵称',
        icon: "error"
      })
      return
    }

    api.request1({
      "nickName": that.data.userNickname,
      "path": "user/updateUserName",
      "token": wx.getStorageSync('token')
    }, function (result) {

      if (result.code == '0') {
        that.closeUploadImg();

        setTimeout(() => {
          wx.showToast({
            title: '设置成功',
          })
        }, 1);


        wx.setStorageSync('nickName', that.data.userNickname)
      } else if (result.code == '301') {
        wx.showModal({
          title: '提示',
          content: result.msg,
          showCancel: false,
          confirmText: '我知道了',
          complete: (res) => {

            if (res.confirm) {

            }
          }
        })
      } else {}
    }, function (error) {})

  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    this.setData({
      avatarUrl,
    })
    this.getOSS(avatarUrl)
  },
  // chooseImage() {
  //   wx.chooseMedia({
  //     count: 1,
  //     mediaType: ['image'],
  //     sizeType: ['compressed'], //可以指定是原图还是压缩图，这里用压缩
  //     sourceType: ['album', 'camera'], //从相册选择
  //     success: (res) => {
  //       //console.log("选择图片成功", res)
  //       let avatarUrl = res.tempFiles[0].tempFilePath
  //       this.setData({
  //         avatarUrl: avatarUrl
  //       })
  //       this.getOSS(avatarUrl)
  //     }
  //   })
  // },
  getOSS: function (avatarUrl) {
    var that = this
    api.request1({
      "path": "user/getOSS",
      "token": wx.getStorageSync('token')
    }, function (result) {
      if (result.code == '0') {
        //host,signature,policy,accessId,dir, path
        that.uploadImg(result.data.host, result.data.signature, result.data.policy, result.data.accessId, result.data.dir, avatarUrl);
      } else if (result.code == '301') {
        wx.showModal({
          title: '提示',
          content: result.msg,
          showCancel: false,
          confirmText: '我知道了',
          complete: (res) => {

            if (res.confirm) { }
          }
        })
      }
    }, function (error) {})
  },
  closeUploadImg: function () {
    var that = this
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeDown(); //调用显示动画
    }, 10)
    that.setData({
      hideUplooadModal: true,
      animationData: that.animation.export()
    })
  },
  uploadImg: function (host1, signature1, policy1, accessId1, dir1, path) {
    var that = this
    const host = host1;
    const signature = signature1;
    const ossAccessKeyId = accessId1;
    const policy = policy1;
    var imgName = new Date().getTime() + '.png';
    const key = dir1 + imgName;
    //console.log(key)
    const securityToken = '';
    const filePath = path; // 待上传文件的文件路径。
    wx.uploadFile({
      url: host, // 开发者服务器的URL。
      filePath: filePath,
      name: 'file', // 必须填file。
      formData: {
        key,
        policy,
        OSSAccessKeyId: ossAccessKeyId,
        signature,
        // 'x-oss-security-token': securityToken // 使用STS签名时必传。
      },
      success: (res) => {
        //console.log('msg='+res.errMsg+',code='+res.statusCode);
        if (res.statusCode === 204) {
          //console.log('上传成功');
          api.request1({
            "imgName": imgName,
            "path": "user/updateUserHeadImg",
            "token": wx.getStorageSync('token')
          }, function (result) {
            if (result.code == '0') {
              that.data.isUploadAvatar = true
              wx.setStorageSync('avatarUrl', result.msg)
            } else if (result.code == '301') {
              wx.showModal({
                title: '提示',
                content: result.msg,
                showCancel: false,
                confirmText: '我知道了',
                complete: (res) => {

                  if (res.confirm) { }
                }
              })
            }
          }, function (error) {})
        }
      },
      fail: err => {
        //console.log(err);
      }
    });
  },
  selectProduct: function (e) {
    var that = this

    if (wx.getStorageSync('avatarUrl').indexOf('txeimg.llmmwl.com/leaderHeadImg/random') != -1) {
      var animation = wx.createAnimation({
        duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
        timingFunction: 'ease', //动画的效果 默认值是linear
      })
      this.animation = animation
      setTimeout(function () {
        that.fadeIn(); //调用显示动画
      }, 10)
      that.setData({
        hideUplooadModal: false,
        animationData: that.animation.export()
      })
      return
    }

    var idx = e.currentTarget.dataset.id;
    that.data.proDetailIndex = idx;
    var product = that.data.targetData.productList[idx];
    if (product.specsList.length > 1) {
      that.data.showGuige = true;
      that.data.showGuige2 = true;
      //console.log("ee===",product.specsList);
      that.data.lastSpecsNum = 0;
      for (let i = 0; i < that.data.targetData.productList.length; i++) {
        var productData = that.data.targetData.productList[i]
        if (productData.specsList.length > 1) {
          for (let j = 0; j < productData.specsList.length; j++) {
            var singleProduct = productData.specsList[j]

            for (let k = 0; k < that.data.targetData.specsList.length; k++) {
              var modifyProduct = that.data.targetData.specsList[k];
              if (modifyProduct.specsId == singleProduct.specsId) {
                if (modifyProduct.state == 4) {
                  singleProduct.state = 4;
                }
              }
            }

            if (singleProduct.closeFlag == 1 && singleProduct.state != 0) {
              console.log('dde==' + singleProduct.state)
              if (singleProduct.state == 4) {
                singleProduct.state = 4;
              } else {
                singleProduct.state = 8;
              }
            }

            if (singleProduct.state == 8) {
              //console.log('3333')
              //console.log('singleProduct.userOrderNum2='+singleProduct.userOrderNum2);
              //console.log('singleProduct.jiedanOrderNum='+singleProduct.jiedanOrderNum);
              singleProduct.isCanAdd = singleProduct.userOrderNum2 >= singleProduct.jiedanOrderNum ? false : true;
              //console.log('singleProduct.isCanAdd='+singleProduct.isCanAdd)
            }
            that.data.lastSpecsNum = that.data.lastSpecsNum + singleProduct.userOrderNum2

            //修正操作购物车后的数据展示
            var ishave = false

            for (let k = 0; k < that.data.modifyProducts.length; k++) {
              var mProduct = that.data.modifyProducts[k];
              if (mProduct.specsId == singleProduct.specsId) {
                ishave = true
              }
            }
            
            if (ishave == false) {
              singleProduct.userOrderNum2 = 0
            }

            for (let k = 0; k < that.data.modifyProducts.length; k++) {
              var mProduct = that.data.modifyProducts[k];

              if (mProduct.specsId == singleProduct.specsId) {
                singleProduct.userOrderNum2 = mProduct.userOrderNum
              }
            }

          }
        }
      }

      var animation = wx.createAnimation({
        duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
        timingFunction: 'ease', //动画的效果 默认值是linear
      })
      this.animation = animation
      setTimeout(function () {
        that.fadeIn3(); //调用显示动画
      }, 10)
      if (that.data.showProDetail) {
        that.setData({
          showGuige2: that.data.showGuige2,
          specsList: product.specsList,
          selectIndex: idx,
          targetData: that.data.targetData,
          isModify: that.data.isModify,
          value: that.data.targetData.productList[that.data.proDetailIndex],
        })
      } else {
        that.setData({
          showGuige: that.data.showGuige,
          specsList: product.specsList,
          selectIndex: idx,
          targetData: that.data.targetData,
          isModify: that.data.isModify,
          value: that.data.targetData.productList[that.data.proDetailIndex],
        })
      }



    } else {

      var isModify = false;
      var singleProduct = product.specsList[0];
      singleProduct.productName = product.name;
      singleProduct.userOrderNum = 1;
      singleProduct.showChangeNum = true;
      singleProduct.imgUrl = product.imageList[0].url;
      if (that.data.selectIndexs.includes(idx) == false) {
        that.data.selectIndexs.push(idx)
      }


      //
      var isModify = false;
      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var modifyProduct = that.data.modifyProducts[i];
        if (modifyProduct.specsId == singleProduct.specsId) {
          isModify = true
        } else {

        }
      }
      //console.log('11111');
      if (isModify == false) {
        //console.log('第一次进来选择商品');
        that.data.modifyProducts.unshift(singleProduct)
      }

      //比较两个数组是否有差异

      //console.log('111==',that.data.targetData.specsList);
      //console.log('222==',that.data.modifyProducts);

      if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
        //console.log('6666');
        isModify = true;
      } else {
        // isModify = false;
        for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
          var specsProduct = that.data.targetData.specsList[i];
          for (let j = 0; j < that.data.modifyProducts.length; ++j) {
            var modifyProduct = that.data.modifyProducts[j];
            if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
              isModify = true
              break;
            }
          }
        }
      }
      //
      var totalNum = 0;
      var totalPrice = 0;
      var containNoPricePro = false;
      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var pro = that.data.modifyProducts[i];
        if (pro.isLastOrder != 1) {
          totalNum += pro.userOrderNum;
          totalPrice += pro.userOrderNum * pro.price;
          console.log('ccc==' + pro.type)
          if (pro.type != 2) {
            console.log('ttt==' + pro.type)
            containNoPricePro = true
          }
        }

      }
      that.data.isModify = isModify;
      console.log('sss==' + isModify)
      if (isModify == true) {
        that.data.targetData.isScroll = false;
      }

      // that.judgeOrderState();
      that.data.targetData.state = 1;
      console.log('www=' + that.data.targetData.isScroll)
      that.setData({
        showChangeNum: singleProduct.userOrderNum > 0 ? true : false,
        userOrderNum: singleProduct.userOrderNum,
        selectIndex: idx,
        targetData: that.data.targetData,
        totalProductNum: totalNum,
        isModify: isModify,
        value: that.data.targetData.productList[that.data.proDetailIndex],
        totalPrice: totalPrice,
        containNoPricePro: containNoPricePro
      })

      that.addProductAnimation(e);
    }

  },

  submitOrder: function (e) {
    var that = this
    // if(!clickThrottle.clickThrottle()){
    //   return
    // }

    var selectPro = [];
    for (var i = 0; i < that.data.modifyProducts.length; i++) {
      var pro = that.data.modifyProducts[i];
      if (pro.isLastOrder != 1) {
        selectPro.push(pro)
      }
    }
    console.log('rrr==' + JSON.stringify(selectPro))
    wx.navigateTo({
      url: '/pages/ConfirmOrderPage/ConfirmOrderPage?data=' + JSON.stringify(selectPro) + '&tuangouId=' + that.data.tuangouID + '&code=' + that.data.targetData.code,
    })
    getApp().globalData.isRelaunch = false

  },
  getTargetDetail: function (tuangouID) {
    var that = this;
    api.request1({
      "tuangouId": tuangouID,
      "path": "user/tuangouDetail",
      "token": wx.getStorageSync('token')
    }, function (result) {
      // wx.stopPullDownRefresh();
      if (result.code == '0') {

        wx.setStorageSync('token', result.data.token)
        that.data.targetData = {}
        that.data.targetData = result.data

        if (that.data.targetData.productList.length == 0) {
          wx.showModal({
            title: '温馨提示',
            content: '该团购内已无商品',
            confirmText: '我知道了',
            showCancel: false,
            complete: (res) => {
              if (res.cancel) {}

              if (res.confirm) {}
            }
          })
          return;
        }

        //第一次进入 清除以前下单的商品数量
        var product = that.data.targetData;
        for (let i = 0; i < product.productList.length; ++i) {
          var pro = product.productList[i];
          pro.totalUserOrderNum = 0;
          for (let j = 0; j < product.productList[i].specsList.length; ++j) {
            var singleProduct = product.productList[i].specsList[j];
            singleProduct.userOrderNum = 0;
          }
        }


        that.data.modifyProducts = [];
        that.data.hasOrderedProduct = that.data.targetData.specsList.length > 0 ? true : false;
        for (var i = 0; i < that.data.targetData.specsList.length; i++) {
          var pro = that.data.targetData.specsList[i];
          pro.isLastOrder = 1;
          if (pro.tuangouId == tuangouID) {
            that.data.hasBenQiOrder = true;
          }
        }

        if (that.data.hasBenQiOrder == true && that.data.buyProAgain == false) {
          wx.reLaunch({
            url: '/pages/CurrentOrderList/CurrentOrderList?tuangouId=' + tuangouID,
          })
          return
        }

        if (that.data.targetData.specsList.length > 0) {
          that.data.modifyProducts = JSON.parse(JSON.stringify(that.data.targetData.specsList));
        }

        wx.setNavigationBarTitle({
          title: that.data.targetData.tuangouName,
        })


        if (that.data.modifyProducts.length > 0) {
          that.data.lastExistNum = true;
        }
        // 后台缺少price字段 自己处理拿到price
        for (let k = 0; k < that.data.modifyProducts.length; k++) {
          var buyedPro = that.data.modifyProducts[k];


          for (let i = 0; i < that.data.targetData.productList.length; i++) {
            var productData = that.data.targetData.productList[i]
            for (let j = 0; j < productData.specsList.length; j++) {
              var singleProduct = productData.specsList[j]

              if (buyedPro.specsId == singleProduct.specsId) {
                buyedPro.price = singleProduct.price
                buyedPro.jiedanOrderNum = singleProduct.userOrderNum;
                if (buyedPro.state > 2) {
                  productData.state = buyedPro.state;
                }

                console.log('cccc=' + buyedPro.state)
              }
            }
          }
        }
        that.data.targetData.productList.sort(function (a, b) {
          return a.orders - b.orders
        });

        for (let i = 0; i < that.data.targetData.productList.length; i++) {
          var productData = that.data.targetData.productList[i]

          if (productData.imageList.length == 0) {
            var imageData = {}
            imageData.url = ''
            imageData.type = 2
            productData.imageList.push(imageData)
          }

          for (let j = 0; j < productData.specsList.length; j++) {
            var singleProduct = productData.specsList[j]
            //console.log('fvfvfv',singleProduct.userOrderNum)
            singleProduct.jiedanOrderNum = singleProduct.userOrderNum;
            //console.log('eeeee',singleProduct.jiedanOrderNum)
            singleProduct.isCanAdd = singleProduct.userOrderNum >= singleProduct.jiedanOrderNum ? false : true;
          }

          if (productData.specsList.length > 1) {
            var mulNum = 0;
            var priceList = [];
            var showWeight = false; // 是否显示“称重计价”标签
            for (let j = 0; j < productData.specsList.length; j++) {
              var singleProduct = productData.specsList[j]
              singleProduct.userOrderNum2 = singleProduct.userOrderNum;
              mulNum += singleProduct.userOrderNum;
              priceList.push(singleProduct.price)
              if (singleProduct.type == 0) {
                showWeight = true
              }
            }
            productData.showWeight = showWeight;
            productData.totalUserOrderNum = mulNum;
            productData.minSpecPrice = Math.min(...priceList);

          } else {
            var showWeight = false;
            var singleProduct = productData.specsList[0]
            if (singleProduct.type == 0) {
              showWeight = true
            }
            productData.showWeight = showWeight;
          }
        }
        //console.log('productData.minSpecPrice'+productData.minSpecPrice);
        if (that.data.targetData.orderList.length > 0) {
          for (let i = 0; i < that.data.targetData.orderList.length; i++) {
            var orderInfo = that.data.targetData.orderList[i];
            if (orderInfo.nickName.length > 2) {
              var name = orderInfo.nickName
              orderInfo.nickName = name.substr(0, 2)
              orderInfo.nickName = orderInfo.nickName + '**'
            }

            var dateStr = that.getDifferDate(orderInfo.time)
            orderInfo.time = dateStr
          }
        }

        if (that.data.targetData.orderList.length > 10) {
          that.data.targetData.orderList1 = that.data.targetData.orderList.slice(0, 11)
          //console.log('that.data.targetData.orderList1=='+that.data.targetData.orderList1);
        }
        //  that.judgeOrderState();

        var reachTargetArr = [];
        var userOrderNum = 0;
        for (let i = 0; i < that.data.modifyProducts.length; ++i) {
          var pro = that.data.modifyProducts[i];
          userOrderNum += pro.userOrderNum
          if (pro.state >= 2) {
            reachTargetArr.push(pro)
          }
        }

        var isEnded = that.data.targetData.state == 0 ? false : true
        console.log('isEnded==' + isEnded);
        var specNum = 0;
        for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
          var myProduct = that.data.targetData.specsList[i];
          if (myProduct.state == '8' || myProduct.state == '0') {
            specNum++;
          }
        }

        if (isEnded == true) {
          that.setData({
            reachTargetArr: reachTargetArr,
            targetData: that.data.targetData,
            selectIndex: 9999,
            lastOrderNum: userOrderNum,
            totalProductNum: 0,
            isModify: false,
            isTriggered: false,
            targetEnded: that.data.targetData.state == 0 ? true : false,
            btmHeight: 120,
            currentIndex: 0,
            isHasJieOrCancel: (specNum > 0 && specNum == that.data.targetData.specsList.length) ? true : false,
            isModify: false,
            seeMoreRecorde: false,
            isDelete: false,
            comeInCorrectScene: true,
            // comeInCorrectScene:that.data.comeInCorrectScene,
            // isCanAdd:false
            showStyle: that.data.targetData.productList[0].style,
            hideModal2: true,
            tuangouName: that.data.targetData.tuangouName
          })
        } else {
          console.log('that.data.comeInCorrectScene=', +that.data.comeInCorrectScene)
          that.setData({
            targetData: that.data.targetData,
            isTriggered: false,
            targetEnded: true,
            // comeInCorrectScene:that.data.comeInCorrectScene,
            comeInCorrectScene: true,
            isDelete: true,
            zHeight: getApp().globalData.zHeight * 2,
          })
        }

      } else if (result.code == '500') { //删除团购

        // wx.reLaunch({
        //   url: '/pages/NoDataPage/NoDataPage?tuangouID='+tuangouID,
        // })
        that.setData({
          targetData: that.data.targetData,
          isTriggered: false,
          targetEnded: true,
          isDelete: true,
          comeInCorrectScene: that.data.comeInCorrectScene,
          zHeight: getApp().globalData.zHeight * 2,
        })
      } else if (result.code == '600' || result.code == '501') {
        //token失效，重新调用登录接口
        console.log('23323223')
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log('===登录===' + res)
            wx.setStorageSync('code', res.code)

            wx.getSetting({
              success: res => {
                if (res.authSetting['scope.userInfo']) {
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                  wx.getUserInfo({
                    success: res => {
                      // 可以将 res 发送给后台解码出 unionId
                      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                      // 所以此处加入 callback 以防止这种情况
                      var that = this
                      api.request1({
                        "tuangouId": tuangouID,
                        "url": res.userInfo.avatarUrl,
                        "nickName": res.userInfo.nickName.length == 0 ? "" : res.userInfo.nickName,
                        "code": wx.getStorageSync('code'),
                        "path": "user/userLogin"
                      }, function (result) {
                        if (result.code == '0') {

                          wx.setStorageSync('id', result.data.id)
                          wx.setStorageSync('token', result.data.token)
                          wx.setStorageSync('nickName', result.data.nickName)
                          wx.setStorageSync('avatarUrl', result.data.headUrl)
                          wx.setStorageSync('phone', result.data.phone)
                          that.globalData.checkLogin = true;

                          if (that.checkLoginReadyCallback) {
                            that.checkLoginReadyCallback(result);
                          }
                        } else if (result.code = '500') {
                          wx.showToast({
                            title: '当前团购无数据，请到团购微信群打开此小程序',
                            icon: "error"
                          })
                        }
                      }, function (error) {
                        console.log("error===", error);
                      })
                    }
                  })
                } else {
                  var that = this
                  wx.getUserInfo({
                    success: res => {
                      console.log(res.userInfo);
                      api.request1({
                        "tuangouId": tuangouID,
                        "url": res.userInfo.avatarUrl,
                        "nickName": res.userInfo.nickName.length == 0 ? "" : res.userInfo.nickName,
                        "code": wx.getStorageSync('code'),
                        "path": "user/userLogin"
                      }, function (result) {

                        if (result.code == '0') {
                          wx.setStorageSync('id', result.data.id)
                          wx.setStorageSync('token', result.data.token)
                          wx.setStorageSync('nickName', result.data.nickName)
                          wx.setStorageSync('avatarUrl', result.data.headUrl)
                          wx.setStorageSync('phone', result.data.phone)
                          that.globalData.checkLogin = true;
                          if (that.checkLoginReadyCallback) {
                            that.checkLoginReadyCallback(result);
                          } else if (result.code = '500') {
                            wx.showToast({
                              title: '当前团购无数据，请到团购微信群打开此小程序',
                              icon: "error"
                            })
                          }
                        }
                      }, function (error) {
                        console.log("error===", error);
                      })
                    }
                  })
                }
              }
            })
          }
        })
      }
    }, function (error) {
      console.log('error==')
    })
  },
  seeMoreRecorde: function () {
    var that = this;
    that.setData({
      seeMoreRecorde: true
    })
  },
  seeMoreRecorde2: function () {
    var that = this;
    that.setData({
      seeMoreRecorde: false
    })
  },

  getDifferDate: function (firstDate) {
    //1)将两个日期字符串转化为日期对象

    var time = firstDate;
    time = time.replace(/-/g, ':').replace(' ', ':');
    time = time.split(':');
    var time1 = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5]).getTime();

    var endDate = new Date();
    // //2)计算两个日期相差的毫秒数
    var msecNum = endDate.getTime() - time1;
    msecNum = parseInt(msecNum / 1000);
    console.log('parseInt(msecNum/60)==', msecNum / 60)
    if (Math.ceil(msecNum / 60) == 0) {
      return '1分钟前'
    } else if (Math.ceil(msecNum / 60) < 60) {
      return Math.ceil(msecNum / 60) + '分钟前'
    } else if (Math.ceil(msecNum / 60 / 60) < 0) {
      return '1小时前'
    } else if (Math.ceil(msecNum / 60 / 60) < 24) {
      return Math.ceil(msecNum / 60 / 60) + '小时前'
    } else if (Math.ceil(msecNum / 60 / 60 / 24) < 2) {
      return '1天前'
    } else if (Math.ceil(msecNum / 60 / 60 / 24) > 2) {
      return Math.ceil(msecNum / 60 / 60 / 24) + '天前'
    }

  },

  judgeOrderState: function () {
    var that = this;
    var hasArrive = false; //是否到货
    that.data.targetData.cancelNO = false; //是否显示取消订单
    that.data.targetData.reachTake = false;
    that.data.targetData.finishTake = false;
    //配送相关
    that.data.targetData.peisongzhong = false;
    that.data.targetData.yisongda = false;
    //底部状态 
    that.data.targetData.isScroll = false;

    var arriveNum = 0;

    if (that.data.targetData.specsList.length > 0) {
      for (let j = 0; j < that.data.targetData.specsList.length; j++) {
        var spro = that.data.targetData.specsList[j];
        for (let i = 0; i < that.data.modifyProducts.length; ++i) {
          var pro = that.data.modifyProducts[i];
          if (spro.specsId == pro.specsId) {
            if (spro.state >= 2) {
              arriveNum++;
            }
          }

        }
        if (arriveNum >= 1) {
          that.data.targetData.isScroll = true;
        }
      }

    }


    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.state == 7) {
        hasArrive = true
        that.data.targetData.state = 8; //已送达 显示更多团购
        that.data.targetData.cancelNO = true;
        that.data.targetData.reachTake = true;
        that.data.targetData.finishTake = true;
        that.data.targetData.arriveProduct = pro.productName;
        break
      }
    }

    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.state == 6 || pro.state == 5) {
        hasArrive = true
        that.data.targetData.state = 7; //配送中 显示更多团购
        that.data.targetData.cancelNO = true;
        that.data.targetData.reachTake = true;
        that.data.targetData.finishTake = true;
        that.data.targetData.arriveProduct = pro.productName;
        break
      }
    }



    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];

      if (that.data.targetData.state == 0) {
        pro.state = 8;
        that.data.targetData.cancelNO = true;
      }

      if (pro.state == 4) {
        that.data.targetData.state = 6;
        that.data.targetData.cancelNO = true;
        that.data.targetData.reachTake = false;
        that.data.targetData.finishTake = true;
        that.data.targetData.arriveProduct = pro.productName;
        break
      }
    }

    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.state == 2) {
        hasArrive = true
        that.data.targetData.state = 3;
        that.data.targetData.cancelNO = true;
        that.data.targetData.reachTake = true;
        that.data.targetData.finishTake = false;
        that.data.targetData.arriveProduct = pro.productName;
        break
      }
    }
    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.state == 3 && hasArrive == false) {
        that.data.targetData.state = 5;
        that.data.targetData.cancelNO = true;
        that.data.targetData.reachTake = false;
        that.data.targetData.finishTake = false;
        that.data.targetData.arriveProduct = pro.productName;
        break
      }
    }

    if (that.data.targetData.state == 2) {
      that.data.targetData.cancelNO = true;
    }
    if (that.data.targetData.closeFlag == 1 && that.data.targetData.state != 0) {

      if (that.data.targetData.state == 3 || that.data.targetData.state == 5 || that.data.targetData.state == 6 || that.data.targetData.state == 7) {
        // that.data.targetData.state=3
        var num = 0;
        for (let i = 0; i < that.data.targetData.specsList.length; i++) {
          var pro = that.data.targetData.specsList[i];
          if (pro.state >= 2) {
            num++;
          }
        }
        if (num >= 1) {
          that.data.targetData.isScroll = true;
        }
      } else if (that.data.targetData.state == 4) {
        that.data.targetData.state = 4
        that.data.targetData.isScroll = false;
      } else {
        that.data.targetData.state = 2;
        that.data.targetData.isScroll = false;
      }

    }


    //console.log('that.data.targetData.reachTak',that.data.targetData.reachTake)
    //console.log('that.data.targetData.finishTake',that.data.targetData.finishTake)
  },
  addClick: function (e) {
    var that = this
    var idx = e.currentTarget.dataset.id;
    //console.log("rrrr",that.data.targetData.reachTake);
    var product = that.data.targetData;
    var jiedanOrderNum = 0;
    if (product.productList[idx].specsList.length == 1) {
      var singleProduct = {};
      if (product.specsList.length > 0) {
        singleProduct = product.productList[idx].specsList[0];
        jiedanOrderNum = singleProduct.jiedanOrderNum;
        if (singleProduct.state == 2) {
          singleProduct.state = 8;
        }
        singleProduct.productName = product.productList[idx].name;
        //console.log("8888")
        for (let i = 0; i < that.data.modifyProducts.length; ++i) {
          //console.log("55555")
          var modifyProduct = that.data.modifyProducts[i];
          if (modifyProduct.specsId == singleProduct.specsId) {
            //console.log("66666")
            singleProduct = modifyProduct;
          } else {}
        }

      } else {
        singleProduct = product.productList[idx].specsList[0];
        singleProduct.productName = product.productList[idx].name;
      }


      singleProduct.userOrderNum++;
      that.data.totalProductNum++;
      var isModify = false;
      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var modifyProduct = that.data.modifyProducts[i];
        if (modifyProduct.specsId == singleProduct.specsId) {
          isModify = true
        } else {

        }
      }
      //console.log('11111');
      if (isModify == false) {
        //console.log('第一次进来选择商品');
        that.data.modifyProducts.unshift(singleProduct)
      }

      // if(that.data.modifyProducts.length>0){
      //   var originProduct = product.productList[idx].specsList[0];
      //   originProduct.userOrderNum++;
      // }

      //比较两个数组是否有差异

      //console.log('111==',that.data.targetData.specsList);
      //console.log('222==',that.data.modifyProducts);

      if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
        //console.log('6666');
        isModify = true;
      } else {
        isModify = false;
        for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
          var specsProduct = that.data.targetData.specsList[i];
          for (let j = 0; j < that.data.modifyProducts.length; ++j) {
            var modifyProduct = that.data.modifyProducts[j];
            if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
              isModify = true
              break;
            }
          }
        }
      }


      //console.log('singleProduct.userOrderNum==',singleProduct.userOrderNum);

      var totalNum = 0;
      var totalPrice = 0;
      var containNoPricePro = false;
      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var pro = that.data.modifyProducts[i];
        if (pro.isLastOrder != 1) {
          totalNum += pro.userOrderNum;
          totalPrice += pro.userOrderNum * pro.price;
          if (pro.type != 2) {
            containNoPricePro = true
          }
        }



      }

      var originProduct = product.productList[idx].specsList[0];
      originProduct.userOrderNum = singleProduct.userOrderNum;
      that.judgeOrderState();
      that.data.targetData.state = 1;
      //console.log('that.data.targetData.state==',that.data.targetData.state);
      //console.log('jiedanOrderNum==',jiedanOrderNum);
      var boolCanAdd = (singleProduct.userOrderNum >= jiedanOrderNum) ? false : true;
      //console.log('boolCanAdd==',boolCanAdd);
      singleProduct.isCanAdd = boolCanAdd;

      for (let i = 0; i < that.data.targetData.productList.length; i++) {
        var pro = that.data.targetData.productList[i];
        var secPro = pro.specsList[0];
        if (secPro.specsId == singleProduct.specsId) {
          secPro.isCanAdd = singleProduct.isCanAdd;
        }

      }

      // if(product.productList[idx].state=='3'){
      //   that.data.isPartModify = true;
      //   that.data.targetData.isScroll = false;
      //   that.setData({
      //     isPartModify:true,
      //     targetData:that.data.targetData
      //   })
      // }

      that.data.isModify = isModify;

      if (isModify == true) {
        that.data.targetData.isScroll = false;
      }

      console.log('ssss==' + isModify);
      that.setData({
        userOrderNum: singleProduct.userOrderNum,
        selectIndex: idx,
        totalProductNum: totalNum,
        isModify: isModify,
        targetData: that.data.targetData,
        isCanAdd: boolCanAdd,
        value: that.data.targetData.productList[that.data.proDetailIndex],
        totalPrice: totalPrice,
        containNoPricePro: containNoPricePro
      })

      that.addProductAnimation(e);
    }
  },
  addProductAnimation: function (e) {
    var that = this
    if (Math.abs(that.data.bus_y - e.touches["0"].clientY) > 20) {
      that.data.keyFrames = [];
      that.data.bus_y = e.touches["0"].clientY;
      let points = ballFallAnimation.touchOnGoods({
          x: e.touches["0"].clientX - 10,
          y: e.touches["0"].clientY - 40,
        },
        that.busPos,
        40
      );
      var index = 0,
        bezier_points = points["bezier_points"];

      var len = bezier_points.length;
      index = len;

      // 放入关键帧
      for (let i = index - 1; i > -1; i--) {
        that.data.keyFrames.push({
          left: bezier_points[i]["x"] + "px",
          top: bezier_points[i]["y"] + "px",
          opacity: i === 0 ? 0 : 1,
          offset: 0.1,
        });
      }
    }
    that.startAnimation();
  },

  subtractionClick: function (e) {
    var that = this
    var idx = e.currentTarget.dataset.id;
    that.data.proDetailIndex = idx;
    var product = that.data.targetData;
    //console.log('that.data.modifyProducts==',that.data.modifyProducts)
    if (product.productList[idx].specsList.length == 1) {

      var singleProduct = {};
      var jiedanOrderNum = 0;
      if (product.specsList.length > 0) {
        singleProduct = product.productList[idx].specsList[0];
        jiedanOrderNum = singleProduct.jiedanOrderNum;
        for (let i = 0; i < that.data.modifyProducts.length; ++i) {
          var modifyProduct = that.data.modifyProducts[i];
          if (modifyProduct.specsId == singleProduct.specsId) {
            //console.log('12321');
            singleProduct = modifyProduct;
          } else {}
        }

      } else {
        singleProduct = product.productList[idx].specsList[0];
      }

      if (singleProduct.userOrderNum != 0) {
        that.data.totalProductNum--;
        if (that.data.totalProductNum == 0) {
          that.data.totalProductNum = 0;
        }
        singleProduct.userOrderNum--;
      }

      //console.log("that.data.totalProductNum==",that.data.totalProductNum)
      if (singleProduct.userOrderNum <= 0) {
        //console.log("that.data.totalProductNum2==",that.data.totalProductNum)
        for (let i = 0; i < that.data.modifyProducts.length; ++i) {
          var modifyProduct = that.data.modifyProducts[i];
          if (modifyProduct.specsId == singleProduct.specsId) {
            //console.log('343434');
            that.data.modifyProducts.splice(i, 1)
          }
        }
      }
      //console.log('that.data.modifyProducts2==',that.data.modifyProducts)
      var isModify = false;
      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var modifyProduct = that.data.modifyProducts[i];
        if (modifyProduct.specsId == singleProduct.specsId) {
          //console.log('555');
          isModify = true
        } else {

        }
      }


      //比较两个数组是否有差异

      //console.log('111==',that.data.targetData.specsList);
      //console.log('222==',that.data.modifyProducts);

      if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
        //console.log('6666');
        isModify = true;
      } else {
        isModify = false;
        for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
          var specsProduct = that.data.targetData.specsList[i];
          for (let j = 0; j < that.data.modifyProducts.length; ++j) {
            var modifyProduct = that.data.modifyProducts[j];
            if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
              isModify = true
              //console.log('777');
              break;
            }
          }
        }
      }

      var totalNum = 0;
      var totalPrice = 0;
      var containNoPricePro = false;
      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var pro = that.data.modifyProducts[i];
        if (pro.isLastOrder != 1) {
          totalNum += pro.userOrderNum;
          totalPrice += pro.userOrderNum * pro.price;
          if (pro.type != 2) {
            containNoPricePro = true
          }
        }

      }

      // if(that.data.modifyProducts.length>0){
      //   var originProduct = product.productList[idx].specsList[0];
      //   originProduct.userOrderNum--;
      // }

      var originProduct = product.productList[idx].specsList[0];
      originProduct.userOrderNum = singleProduct.userOrderNum;
      that.data.isModify = isModify;

      that.judgeOrderState();
      that.data.targetData.state = 1;

      //console.log('jiedanOrderNum==',jiedanOrderNum);
      var boolCanAdd = (singleProduct.userOrderNum >= jiedanOrderNum) ? false : true;
      //console.log('boolCanAdd==',boolCanAdd);
      singleProduct.isCanAdd = boolCanAdd;
      //console.log('singleProduct.isCanAdd==',singleProduct.isCanAdd);
      //console.log('singleProduct==',singleProduct);
      for (let i = 0; i < that.data.targetData.productList.length; i++) {
        var pro = that.data.targetData.productList[i];
        var secPro = pro.specsList[0];
        if (secPro.specsId == singleProduct.specsId) {
          secPro.isCanAdd = singleProduct.isCanAdd;
        }

      }
      console.log('sds==' + that.data.isModify)

      if (isModify == true) {
        that.data.targetData.isScroll = false;
      }
      that.setData({
        userOrderNum: singleProduct.userOrderNum,
        selectIndex: idx,
        totalProductNum: totalNum,
        showChangeNum: singleProduct.userOrderNum > 0 ? true : false,
        isModify: isModify,
        targetData: that.data.targetData,
        isCanAdd: boolCanAdd,
        value: that.data.targetData.productList[that.data.proDetailIndex],
        totalPrice: totalPrice,
        containNoPricePro: containNoPricePro
      })
    }
  },
  addClick1: function (e) {
    var that = this
    var idx = e.currentTarget.dataset.id; //规格id
    var index = e.currentTarget.dataset.index;
    //console.log("idx==",idx);
    //console.log("index==",index);
    var jiedanOrderNum = 0;
    for (let i = 0; i < that.data.targetData.productList.length; ++i) {
      var product = that.data.targetData.productList[i];
      for (let j = 0; j < product.specsList.length; ++j) {
        var singleProduct = product.specsList[j];
        var originProduct = product.specsList[j];
        singleProduct.productName = product.name;
        if (singleProduct.specsId == idx) {

          if (that.data.targetData.specsList.length > 0) {
            for (let i = 0; i < that.data.modifyProducts.length; ++i) {
              var modifyProduct = that.data.modifyProducts[i];
              if (modifyProduct.specsId == singleProduct.specsId) {
                singleProduct = modifyProduct;
              } else {

              }
            }
          }

          singleProduct.userOrderNum++;
          that.data.totalProductNum++;
          var isModify = false;
          for (let i = 0; i < that.data.modifyProducts.length; ++i) {
            var modifyProduct = that.data.modifyProducts[i];
            if (modifyProduct.specsId == singleProduct.specsId) {
              isModify = true
            } else {

            }
          }
          //console.log('11111');
          if (isModify == false) {
            //console.log('234222');
            that.data.modifyProducts.unshift(singleProduct)
          }

          //比较两个数组是否有差异

          //console.log('111==',that.data.targetData.specsList);
          //console.log('222==',that.data.modifyProducts);

          if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
            //console.log('6666');
            isModify = true;
          } else {
            isModify = false;
            for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
              var specsProduct = that.data.targetData.specsList[i];
              for (let j = 0; j < that.data.modifyProducts.length; ++j) {
                var modifyProduct = that.data.modifyProducts[j];
                if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
                  isModify = true
                  break;
                }
              }
            }
          }
          var totalNum = 0;
          var totalPrice = 0;
          var containNoPricePro = false;
          for (let i = 0; i < that.data.modifyProducts.length; ++i) {
            var pro = that.data.modifyProducts[i];
            if (pro.isLastOrder != 1) {
              totalNum += pro.userOrderNum;
              totalPrice += pro.userOrderNum * pro.price;
              if (pro.type != 2) {
                containNoPricePro = true
              }
            }

          }

          //console.log("singleProduct.userOrderNum==",singleProduct.userOrderNum)

          if (originProduct.specsId == idx) {
            originProduct.userOrderNum = singleProduct.userOrderNum;
          }

          //动态更新以选择的多规格数据 下同
          for (let i = 0; i < that.data.targetData.productList.length; i++) {
            var productData = that.data.targetData.productList[i]

            var mulNum = 0;
            for (let j = 0; j < productData.specsList.length; j++) {
              var ssProduct = productData.specsList[j]
              mulNum += ssProduct.userOrderNum;
            }
            productData.totalUserOrderNum = mulNum;
          }
          that.data.isModify = isModify;

          jiedanOrderNum = singleProduct.jiedanOrderNum;
          //console.log('jiedanOrderNum==',jiedanOrderNum);
          //console.log('singleProduct.jiedanOrderNum==',singleProduct.jiedanOrderNum);
          var boolCanAdd = (singleProduct.userOrderNum >= jiedanOrderNum) ? false : true;
          //console.log('boolCanAdd==',boolCanAdd);
          singleProduct.isCanAdd = boolCanAdd;

          for (let i = 0; i < that.data.targetData.productList.length; i++) {
            var pro = that.data.targetData.productList[i];
            for (let j = 0; j < pro.specsList.length; j++) {
              var secPro = pro.specsList[j];

              if (secPro.specsId == singleProduct.specsId) {
                secPro.isCanAdd = singleProduct.isCanAdd;
                secPro.userOrderNum2 = singleProduct.userOrderNum;
              }
            }
          }

          that.judgeOrderState();
          that.data.targetData.state = 1;
          if (that.data.isModify == true) {
            that.data.targetData.isScroll = false;
          }
          singleProduct.isCanAdd = boolCanAdd;

          if (that.data.hasOrderedProduct == true) {
            if (that.data.showModeOrder == true) {
              that.setData({
                userOrderNum: singleProduct.userOrderNum,
                totalProductNum: totalNum,
                isModify: isModify,
                modifyId: index,
                selectedProducts: that.data.modifyProducts,
                targetData: that.data.targetData,
                isCanAdd: boolCanAdd,
                totalPrice: totalPrice,
                containNoPricePro: containNoPricePro
              })
            } else {
              var newSelectProducts = []
              for (let i = 0; i < that.data.modifyProducts.length; i++) {
                var pro = that.data.modifyProducts[i];
                if (pro.isLastOrder != 1) {
                  newSelectProducts.push(pro)
                }
              }
              that.setData({
                userOrderNum: singleProduct.userOrderNum,
                totalProductNum: totalNum,
                isModify: isModify,
                modifyId: index,
                selectedProducts: newSelectProducts,
                targetData: that.data.targetData,
                isCanAdd: boolCanAdd,
                totalPrice: totalPrice,
                containNoPricePro: containNoPricePro
              })
            }
          } else {
            that.setData({
              userOrderNum: singleProduct.userOrderNum,
              totalProductNum: totalNum,
              isModify: isModify,
              modifyId: index,
              selectedProducts: that.data.modifyProducts,
              targetData: that.data.targetData,
              isCanAdd: boolCanAdd,
              totalPrice: totalPrice,
              containNoPricePro: containNoPricePro
            })
          }


          break;
        }
      }
    }

    that.addProductAnimation(e);

  },
  subtractionClick1: function (e) {
    var that = this
    var idx = e.currentTarget.dataset.id; //规格id
    var index = e.currentTarget.dataset.index;
    //console.log('index==',e);
    var jiedanOrderNum = 0;
    for (let i = 0; i < that.data.targetData.productList.length; ++i) {
      var product = that.data.targetData.productList[i];
      for (let j = 0; j < product.specsList.length; ++j) {
        var singleProduct = product.specsList[j];
        var originProduct = product.specsList[j];
        singleProduct.productName = product.name;
        if (singleProduct.specsId == idx) {

          if (that.data.targetData.specsList.length > 0) {
            for (let i = 0; i < that.data.modifyProducts.length; ++i) {
              var modifyProduct = that.data.modifyProducts[i];
              if (modifyProduct.specsId == singleProduct.specsId) {
                //console.log("1222222");
                singleProduct = modifyProduct;
              } else {

              }
            }
          }


          if (singleProduct.userOrderNum != 0) {
            that.data.totalProductNum--;
            if (that.data.totalProductNum == 0) {
              that.data.totalProductNum = 0;
            }
            singleProduct.userOrderNum--;
          }
          if (singleProduct.userOrderNum <= 0) {
            that.data.modifyProducts.splice(index, 1);

            for (let i = 0; i < that.data.targetData.productList.length; ++i) {
              var product = that.data.targetData.productList[i];
              for (let j = 0; j < product.specsList.length; ++j) {
                var ssProduct = product.specsList[j];
                if (ssProduct.specsId == idx) {
                  ssProduct.userOrderNum = 0;
                }
              }
            }
          }

          var isModify = false;
          for (let i = 0; i < that.data.modifyProducts.length; ++i) {
            var modifyProduct = that.data.modifyProducts[i];
            if (modifyProduct.specsId == singleProduct.specsId) {
              isModify = true
            } else {

            }
          }
          //比较两个数组是否有差异
          //console.log('111==',that.data.targetData.specsList);
          //console.log('222==',that.data.modifyProducts);

          if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
            //console.log('6666');
            isModify = true;
          } else {
            isModify = false;
            for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
              var specsProduct = that.data.targetData.specsList[i];
              for (let j = 0; j < that.data.modifyProducts.length; ++j) {
                var modifyProduct = that.data.modifyProducts[j];
                if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
                  isModify = true
                  break;
                }
              }
            }
          }


          var totalNum = 0;
          var totalPrice = 0;
          var containNoPricePro = false;
          var showCleanPro = false
          for (let i = 0; i < that.data.modifyProducts.length; ++i) {
            var pro = that.data.modifyProducts[i];
            if (pro.isLastOrder != 1) {
              totalNum += pro.userOrderNum;
              totalPrice += pro.userOrderNum * pro.price;
              showCleanPro = true
              if (pro.type != 2) {
                containNoPricePro = true
              }
            }

          }
          if (originProduct.specsId == idx) {
            //console.log("singleProduct.userOrderNum==",singleProduct.userOrderNum)
            originProduct.userOrderNum = singleProduct.userOrderNum;
          }

          for (let i = 0; i < that.data.targetData.productList.length; i++) {
            var productData = that.data.targetData.productList[i]
            var mulNum = 0;
            for (let j = 0; j < productData.specsList.length; j++) {
              var ssProduct = productData.specsList[j]
              mulNum += ssProduct.userOrderNum;
            }
            productData.totalUserOrderNum = mulNum;
          }
          jiedanOrderNum = singleProduct.jiedanOrderNum;
          //console.log('jiedanOrderNum==',jiedanOrderNum);
          //console.log('singleProduct.jiedanOrderNum==',singleProduct.jiedanOrderNum);
          var boolCanAdd = (singleProduct.userOrderNum >= jiedanOrderNum) ? false : true;
          //console.log('boolCanAdd==',boolCanAdd);
          singleProduct.isCanAdd = boolCanAdd;

          for (let i = 0; i < that.data.targetData.productList.length; i++) {
            var pro = that.data.targetData.productList[i];
            for (let j = 0; j < pro.specsList.length; j++) {
              var secPro = pro.specsList[j];

              if (secPro.specsId == singleProduct.specsId) {
                secPro.isCanAdd = singleProduct.isCanAdd;
                secPro.userOrderNum2 = singleProduct.userOrderNum;
              }
            }
          }

          that.data.isModify = isModify;
          that.judgeOrderState();
          that.data.targetData.state = 1;
          if (that.data.isModify == true) {
            that.data.targetData.isScroll = false;
          }

          if (that.data.hasOrderedProduct == true) {
            if (that.data.showModeOrder == true) {
              var newSelectProducts = []
              for (let i = 0; i < that.data.modifyProducts.length; i++) {
                var pro = that.data.modifyProducts[i];
                if (pro.isLastOrder != 1) {
                  newSelectProducts.push(pro)
                }
              }
              that.setData({
                showChangeNum: singleProduct.userOrderNum > 0 ? true : false,
                userOrderNum: singleProduct.userOrderNum,
                totalProductNum: totalNum,
                isModify: isModify,
                modifyId: index,
                selectedProducts: that.data.modifyProducts,
                hideModal: newSelectProducts.length > 0 ? false : true,
                targetData: that.data.targetData,
                isCanAdd: boolCanAdd,
                totalPrice: totalPrice,
                containNoPricePro: containNoPricePro,
                showCleanPro: showCleanPro
              })
            } else {
              var newSelectProducts = []
              for (let i = 0; i < that.data.modifyProducts.length; i++) {
                var pro = that.data.modifyProducts[i];
                if (pro.isLastOrder != 1) {
                  newSelectProducts.push(pro)
                }
              }
              that.setData({
                showChangeNum: singleProduct.userOrderNum > 0 ? true : false,
                userOrderNum: singleProduct.userOrderNum,
                totalProductNum: totalNum,
                selectedProducts: newSelectProducts,
                isModify: isModify,
                modifyId: index,
                hideModal: newSelectProducts.length > 0 ? false : true,
                targetData: that.data.targetData,
                isCanAdd: boolCanAdd,
                totalPrice: totalPrice,
                containNoPricePro: containNoPricePro,
                showCleanPro: showCleanPro
              })
            }
          } else {
            that.setData({
              showChangeNum: singleProduct.userOrderNum > 0 ? true : false,
              userOrderNum: singleProduct.userOrderNum,
              totalProductNum: totalNum,
              isModify: isModify,
              modifyId: index,
              selectedProducts: that.data.modifyProducts,
              hideModal: that.data.modifyProducts.length > 0 ? false : true,
              targetData: that.data.targetData,
              isCanAdd: boolCanAdd,
              totalPrice: totalPrice,
              containNoPricePro: containNoPricePro
            })
          }
          break;
        }
      }
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.ballComponent = [];
    // Do something when page ready.
    // 循环获取所有的小球节点
    for (let i = 0; i < this.data.ballAnimationArray.length; i++) {
      // 获取小球节点信息
      this.ballAnimation = this.selectComponent(`#ball-${i}`);
      // 将小球信息存储
      this.ballComponent.push(this.ballAnimation);
    }

    //console.log("eeeee=",this.ballComponent)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    const obj = wx.getEnterOptionsSync()
    console.log(" ID== ", obj.query.id + ",scene==", obj.scene)



    if ((obj.scene == 1044 || obj.scene == 1007 || obj.scene == 1014) && getApp().globalData.isRelaunch == true) {
      that.data.comeInCorrectScene = true;

      if (that.data.tuangouID != undefined) {
        that.data.leaderID = obj.query.userId;
        if (getApp().globalData.checkLogin == true) {
          if (that.data.isClickImage == false) {
            that.getTargetDetail(that.data.tuangouID);
            that.data.isClickImage = false;
          }
        }


      } else {
        if (that.data.isClickImage == false) {
          that.getTargetDetail(obj.query.id);
          that.data.tuangouID = obj.query.id;
          that.data.leaderID = obj.query.userId;
          that.data.isClickImage = false;
        }

      }

    } else {
      that.data.comeInCorrectScene = false;
    }

    // if(getApp().globalData.isRelaunch == false){
    //   getApp().globalData.isRelaunch = true
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  showProductDetail: function (e) {

    var that = this
    that.data.showProDetail = true
    var idx = e.currentTarget.dataset.id;
    that.data.proDetailIndex = idx;
    console.log('dsdsd=' + e.currentTarget.dataset.id);
    var screen = screenUtil.screenUtil()
    var scrHeight = screen.windowHeight
    that.setData({
      value: that.data.targetData.productList[idx],
      hideModal2: false,
      targetData: that.data.targetData,
      idx: idx,
      zHeight: getApp().globalData.zHeight * 2,
      scrHeight: scrHeight
    })
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn2(); //调用显示动画
    }, 10)
  },
  hideProductDetail: function () {

    var that = this;
    that.data.showProDetail = false
    console.log('ccccccc')
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown2(); //调用隐藏动画 
    setTimeout(function () {
      that.setData({
        hideModal2: true
      })
    }, 250) //先执行下滑动画，再隐藏模块
  },

  // 显示遮罩层
  showModal: function () {
    var that = this;
    // that.data.selectedProducts = [];
    // //遍历任务商品，找出选择过的商品
    // for(let i=0;i<that.data.targetData.productList.length;++i){
    //   var product = that.data.targetData.productList[i];
    //   for(let j=0; j<product.specsList.length;++j){
    //     var singleProduct = product.specsList[j];
    //     singleProduct.productName = product.name;
    //     if(singleProduct.userOrderNum>0&&singleProduct.state != '4'){
    //       that.data.selectedProducts.push(singleProduct);
    //     }
    //   }
    // }

    // if(that.data.selectedProducts.length==0){
    //   return;
    // }
    //console.log("eee==",that.data.modifyProducts)

    var newSelectProduct = false //是否有当前新添加的商品
    var newSelectProducts = []
    var showCleanPro = false
    for (let i = 0; i < that.data.modifyProducts.length; i++) {
      var pro = that.data.modifyProducts[i];
      if (pro.state == 8) {
        pro.isCanAdd = pro.userOrderNum >= pro.jiedanOrderNum ? false : true;
      }

      if (pro.isLastOrder != 1) {
        newSelectProduct = true;
        newSelectProducts.push(pro)
        showCleanPro = true;
      }
    }

    //console.log("that.data.cancelNO==",that.data.targetData.cancelNO)
    if (newSelectProduct == true || that.data.modifyProducts.length == 0) {
      that.data.showTuanwuche = !that.data.showTuanwuche
    } else {
      that.data.showTuanwuche = false
      console.log('fff' + that.data.targetData.id)
      wx.navigateTo({
        url: '/pages/OrderProduct/OrderProduct?tuangouId=' + that.data.targetData.id,
      })
      return
    }

    if (!that.data.showTuanwuche == false) {
      that.data.showModeOrder = false
      that.setData({
        hideModal: !that.data.showTuanwuche,
        selectedProducts: newSelectProducts,
        cancelNO: that.data.targetData.cancelNO,
        targetData: that.data.targetData,
        hasOrderedProduct: that.data.hasOrderedProduct,
        showModeOrder: false,
        showCleanPro: showCleanPro
      })
      var animation = wx.createAnimation({
        duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
        timingFunction: 'ease', //动画的效果 默认值是linear
      })
      this.animation = animation
      setTimeout(function () {
        that.fadeIn(); //调用显示动画
      }, 10)
    } else {
      that.setData({
        selectedProducts: newSelectProducts,
        cancelNO: that.data.targetData.cancelNO,
        targetData: that.data.targetData
      })
      that.hideModal();
    }

  },

  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    that.data.showTuanwuche = false
    var animation = wx.createAnimation({
      duration: 200, //动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown(); //调用隐藏动画 
    setTimeout(function () {
      that.setData({
        hideModal: true
      })
    }, 250) //先执行下滑动画，再隐藏模块

  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },

  fadeIn2: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData2: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },

  fadeIn3: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData3: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(500).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  fadeDown2: function () {
    this.animation.translateY(800).step()
    this.setData({
      animationData2: this.animation.export(),
    })
  },
  fadeDown3: function () {
    this.animation.translateY(800).step()
    this.setData({
      animationData3: this.animation.export(),
    })
  },
  showBigContent: function (e) {
    var that = this
    var curIdx = e.currentTarget.dataset.id;
    var proIndex = e.currentTarget.dataset.index;
    //console.log("curIdx=", curIdx);
    that.setData({
      currentClickIndex: curIdx,
      showBigContent: true,
      targetData: that.data.targetData,
      proIndex: proIndex
    })
  },
  closeBigContent: function (e) {
    this.setData({
      showBigContent: false
    })
  },
  clickimage: function (e) {
    var that = this
    that.data.isClickImage = true;
    var imgList = e.currentTarget.dataset.list;
    var imageList = [];
    for (let i = 0; i < imgList.length; ++i) {
      if (imgList[i].type == '0') {
        imageList.push(imgList[i].url)
      }
    }
    wx.previewImage({
      current: e.currentTarget.dataset.src, //点击显示的图片
      urls: imageList
    })
  },
  addClick2: function (e) {
    var that = this
    //console.log("e=====",e)
    var idx = e.currentTarget.dataset.index; //规格index
    var proindex = e.currentTarget.dataset.id; //商品index 
    //console.log("规格index=",idx)
    //console.log("商品index=",proindex)
    var jiedanOrderNum = 0;
    var product = that.data.targetData;
    var parentProduct = product.productList[proindex];
    var singleProduct = parentProduct.specsList[idx];

    singleProduct.productName = parentProduct.name;

    // for(let i=0;i<that.data.modifyProducts.length;++i){
    //   //console.log("55555")
    //   var modifyProduct = that.data.modifyProducts[i];
    //   if(modifyProduct.specsId == singleProduct.specsId){
    //     singleProduct = modifyProduct;
    //   }else{}
    // }

    singleProduct.userOrderNum2++;
    // var isModify = false;
    // for(let i=0;i<that.data.modifyProducts.length;++i){
    //   var modifyProduct = that.data.modifyProducts[i];
    //   if(modifyProduct.specsId == singleProduct.specsId){
    //     isModify = true
    //   }else{

    //   }
    // }
    // //console.log('11111');
    // if(isModify == false){
    //   //console.log('第一次进来选择商品');
    //   that.data.modifyProducts.push(singleProduct)
    // }
    // if(that.data.targetData.specsList.length!=that.data.modifyProducts.length){
    //   //console.log('6666');
    //   isModify = true;
    // }else{
    //   isModify = false;
    //   for(let i=0;i<that.data.targetData.specsList.length;++i){
    //     var specsProduct = that.data.targetData.specsList[i];
    //     for(let j=0;j<that.data.modifyProducts.length;++j){
    //       var modifyProduct = that.data.modifyProducts[j];
    //       if(specsProduct.specsId == modifyProduct.specsId &&specsProduct.userOrderNum != modifyProduct.userOrderNum){
    //         //console.log('7777');
    //         isModify = true
    //         break;
    //       }
    //     }
    //   }
    // }
    var totalNum = 0;

    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.isLastOrder != 1) {
        totalNum += pro.userOrderNum;
      }
    }

    for (let i = 0; i < parentProduct.specsList.length; ++i) {
      var vPro = parentProduct.specsList[i];
      if (vPro.specsId == singleProduct.specsId) {
        vPro.userOrderNum = singleProduct.userOrderNum;
        break;
      }
    }
    // that.data.isModify = isModify;
    // that.judgeOrderState();
    that.data.targetData.state = 1;
    jiedanOrderNum = singleProduct.jiedanOrderNum
    //console.log('jiedanOrderNum==',singleProduct.jiedanOrderNum)
    var boolCanAdd = (singleProduct.userOrderNum2 >= jiedanOrderNum) ? false : true;
    //console.log('boolCanAdd==',boolCanAdd);
    singleProduct.isCanAdd = boolCanAdd;
    that.setData({
      specsList: parentProduct.specsList,

      // isModify:isModify,
      targetData: that.data.targetData,
      isCanAdd: boolCanAdd
    })



  },
  subtractionClick2: function (e) {
    var that = this
    //console.log("e=====",e)
    var jiedanOrderNum = 0;
    var idx = e.currentTarget.dataset.index; //规格index
    var proindex = e.currentTarget.dataset.id; //商品index 
    //console.log("规格index=",idx)
    //console.log("商品index=",proindex)
    var product = that.data.targetData;
    var parentProduct = product.productList[proindex];
    var singleProduct = parentProduct.specsList[idx];
    singleProduct.productName = parentProduct.name;

    // for(let i=0;i<that.data.modifyProducts.length;++i){
    //   //console.log("55555")
    //   var modifyProduct = that.data.modifyProducts[i];
    //   if(modifyProduct.specsId == singleProduct.specsId){
    //     singleProduct = modifyProduct;
    //   }else{}
    // }

    singleProduct.userOrderNum2--;
    if (singleProduct.userOrderNum2 <= 0) {
      singleProduct.userOrderNum2 = 0;
    }

    // if(singleProduct.userOrderNum<=0){
    //   //console.log("that.data.totalProductNum2==",that.data.totalProductNum)
    //   for(let i=0;i<that.data.modifyProducts.length;++i){
    //     var modifyProduct = that.data.modifyProducts[i];
    //     if(modifyProduct.specsId == singleProduct.specsId){
    //       //console.log('343434');
    //       that.data.modifyProducts.splice(i,1)
    //     }
    //   }
    // }
    // //console.log('that.data.modifyProducts2==',that.data.modifyProducts)
    // var isModify = false;
    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var modifyProduct = that.data.modifyProducts[i];
      if (modifyProduct.specsId == singleProduct.specsId) {
        //console.log('555');
        // isModify = true
      } else {

      }
    }


    //比较两个数组是否有差异

    //console.log('111==',that.data.targetData.specsList);
    //console.log('222==',that.data.modifyProducts);

    if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
      //console.log('6666');
      // isModify = true;
    } else {
      // isModify = false;
      for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
        var specsProduct = that.data.targetData.specsList[i];
        for (let j = 0; j < that.data.modifyProducts.length; ++j) {
          var modifyProduct = that.data.modifyProducts[j];
          if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
            // isModify = true
            //console.log('777');
            //console.log('specsProduct.specsId==',specsProduct.specsId);
            //console.log('modifyProduct.specsId==',modifyProduct.specsId);
            break;
          }
        }
      }
    }

    var totalNum = 0;
    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.isLastOrder != 1) {
        totalNum += pro.userOrderNum;
      }
    }

    for (let i = 0; i < parentProduct.specsList.length; ++i) {
      var vPro = parentProduct.specsList[i];
      if (vPro.specsId == singleProduct.specsId) {
        vPro.userOrderNum = singleProduct.userOrderNum;
        break;
      }
    }
    // that.data.isModify = isModify;

    // that.judgeOrderState();
    that.data.targetData.state = 1;
    jiedanOrderNum = singleProduct.jiedanOrderNum;
    //console.log('jiedanOrderNum==',jiedanOrderNum);
    //console.log('singleProduct.userOrderNum2==',singleProduct.userOrderNum2);
    var boolCanAdd = (singleProduct.userOrderNum2 >= jiedanOrderNum) ? false : true;
    //console.log('boolCanAdd==',boolCanAdd);
    singleProduct.isCanAdd = boolCanAdd;
    that.setData({
      specsList: parentProduct.specsList,
      // totalProductNum:totalNum,
      // isModify:isModify,
      targetData: that.data.targetData,
      isCanAdd: boolCanAdd
    })
    //console.log(that.data.targetData);
  },
  closeGuige: function (e) {

    var that = this
    //console.log("e=====",e)

    for (let i = 0; i < that.data.targetData.productList.length; i++) {
      var productData = that.data.targetData.productList[i]
      if (productData.specsList.length > 1) {
        for (let j = 0; j < productData.specsList.length; j++) {
          var singleProduct = productData.specsList[j]

          if (that.data.modifyProducts.length == 0) {
            singleProduct.userOrderNum2 = 0
          }

          for (let k = 0; k < that.data.modifyProducts.length; k++) {
            var mProduct = that.data.modifyProducts[k];
            if (mProduct.specsId == singleProduct.specsId) {
              singleProduct.userOrderNum2 = mProduct.userOrderNum
            }
          }
        }
      }
    }

    this.data.showGuige = false;
    this.data.showGuige2 = false;
    if (that.data.showProDetail) {
      this.setData({
        showGuige2: this.data.showGuige2,
        // targetData:that.data.targetData,
        // totalProductNum:totalNum
      })
    } else {
      this.setData({
        showGuige: this.data.showGuige,
        // targetData:that.data.targetData,
        // totalProductNum:totalNum
      })
    }

  },
  readyFinish: function (e) {
    var that = this
    that.data.showGuige = false;
    that.data.showGuige2 = false;
    for (let i = 0; i < that.data.targetData.productList.length; i++) {
      var productData = that.data.targetData.productList[i]

      var mulNum = 0;
      var tempNum = 0;
      //console.log("productData=",productData)
      for (let j = 0; j < productData.specsList.length; j++) {
        var singleProduct = productData.specsList[j]
        singleProduct.imgUrl = productData.imageList[0].url
        mulNum += singleProduct.userOrderNum2;
        tempNum += singleProduct.userOrderNum2;
        if (singleProduct.userOrderNum2 > 0) {
          var isModify = false;
          for (let i = 0; i < that.data.modifyProducts.length; ++i) {
            var modifyProduct = that.data.modifyProducts[i];
            if (modifyProduct.specsId == singleProduct.specsId) {
              isModify = true
            } else {

            }
          }
          if (isModify == false) {
            //console.log('第一次进来选择商品');
            that.data.modifyProducts.unshift(singleProduct)
          }
        }

      }

      //console.log("mulNum=",mulNum)
      productData.totalUserOrderNum = mulNum;


      if (productData.specsList.length > 1) {
        for (let j = 0; j < productData.specsList.length; j++) {
          var singleProduct = productData.specsList[j]
          for (let k = 0; k < that.data.modifyProducts.length; k++) {
            var mProduct = that.data.modifyProducts[k];
            if (mProduct.specsId == singleProduct.specsId) {

              if (singleProduct.userOrderNum2 > 0) {
                mProduct.userOrderNum = singleProduct.userOrderNum2
              } else {
                that.data.modifyProducts.splice(k, 1)
              }
            }
          }

        }
      }
    }

    //

    //

    var totalNum = 0;
    var totalPrice = 0;
    var containNoPricePro = false;
    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var pro = that.data.modifyProducts[i];
      if (pro.isLastOrder != 1) {
        totalNum += pro.userOrderNum;
        totalPrice += pro.userOrderNum * pro.price;
        if (pro.type != 2) {
          containNoPricePro = true
        }
      }

    }

    //console.log("targetData=",that.data.targetData)


    var isModify = false;

    // if(isModify == false){
    //   //console.log('第一次进来选择商品');
    //   that.data.modifyProducts.push(singleProduct)
    // }

    //console.log('that.data.targetData.specsList='+that.data.targetData.specsList)
    //console.log('that.data.modifyProducts='+that.data.modifyProducts)
    if (that.data.targetData.specsList.length != that.data.modifyProducts.length) {
      //console.log('6666');
      isModify = true;
    } else {
      isModify = false;
      for (let i = 0; i < that.data.targetData.specsList.length; ++i) {
        var specsProduct = that.data.targetData.specsList[i];
        for (let j = 0; j < that.data.modifyProducts.length; ++j) {
          var modifyProduct = that.data.modifyProducts[j];
          if (specsProduct.specsId == modifyProduct.specsId && specsProduct.userOrderNum != modifyProduct.userOrderNum) {
            //console.log('7777');
            isModify = true
            break;
          }
        }
      }
    }

    that.judgeOrderState();
    that.data.targetData.state = 1;
    that.data.isModify = isModify;
    if (isModify == true) {
      that.data.targetData.isScroll = false;
    }
    console.log('cdcd=' + isModify)

    if (that.data.showProDetail) {
      that.setData({
        showGuige2: that.data.showGuige2,
        targetData: that.data.targetData,
        showChangeNum: false,
        totalProductNum: totalNum,
        isModify: isModify,
        value: that.data.targetData.productList[that.data.proDetailIndex],
        totalPrice: totalPrice,
        containNoPricePro: containNoPricePro
      })
    } else {
      that.setData({
        showGuige: that.data.showGuige,
        targetData: that.data.targetData,
        showChangeNum: false,
        totalProductNum: totalNum,
        isModify: isModify,
        value: that.data.targetData.productList[that.data.proDetailIndex],
        totalPrice: totalPrice,
        containNoPricePro: containNoPricePro
      })
    }


    //console.log("that.data.lastSpecsNum"+that.data.lastSpecsNum)
    //console.log('tempNum'+tempNum)

    if (tempNum > that.data.lastSpecsNum) {
      that.addProductAnimation(e);
    }
  },
  clearAllProducts: function (e) {
    var that = this
    //console.log("wwwww")
    var proTemp = [];
    for (var i = 0; i < that.data.modifyProducts.length; i++) {
      var pro = that.data.modifyProducts[i];
      if (pro.isLastOrder != 1) {
        proTemp.push(pro)
      }
    }

    for (var i = 0; i < proTemp.length; i++) {
      var pro1 = proTemp[i];
      for (var j = 0; j < that.data.modifyProducts.length; j++) {
        var pro2 = that.data.modifyProducts[j];
        if (pro1.specsId == pro2.specsId) {
          that.data.modifyProducts.splice(j, 1);
        }
      }
    }

    var product = that.data.targetData;
    for (let i = 0; i < product.productList.length; ++i) {
      var pro = product.productList[i];
      pro.totalUserOrderNum = 0;
      for (let j = 0; j < product.productList[i].specsList.length; ++j) {
        var singleProduct = product.productList[i].specsList[j];
        singleProduct.userOrderNum = 0;
      }
    }

    that.data.showTuanwuche = false
    that.setData({
      targetData: that.data.targetData,
      totalProductNum: 0,
      hideModal: true,
      totalPrice: 0,
      isModify: false
    })
  },
  confirmOrCancel: function (e) {
    var that = this

    if (that.data.targetData.cancelNO == true && that.data.isModify == false && that.data.targetData.reachTake == true && that.data.isModify == false) {
      that.reachTakeOrder();
      return;
    }

    if (that.data.isModify == false) {
      that.tomorrowAppoint();
      return
    }

    if ((that.data.isModify == false && that.data.targetData.cancelNO == false)) { //修改

      wx.showModal({
        title: '提示',
        content: '确定要修改订单吗？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: function (res) {
          if (res.confirm) {
            //console.log('用户点击确定')
            that.data.isModify = true;
            that.setData({
              targetData: that.data.targetData,
              isModify: true,
            })
          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      })
    } else if (that.data.isModify == true || that.data.isPartModify == true) {
      var submitProducts = [];

      // for(let i=0;i<that.data.targetData.productList.length;++i){
      //   var product = that.data.targetData.productList[i];
      //   for(let j=0; j<product.specsList.length;++j){
      //     var singleProduct = product.specsList[j];
      //     if(singleProduct.userOrderNum>0){
      //       productModel.specsId = singleProduct.specsId;
      //       productModel.num = singleProduct.userOrderNum;
      //       submitProducts.push(productModel);
      //     }
      //   }
      // }

      for (let i = 0; i < that.data.modifyProducts.length; ++i) {
        var productModel = {};
        var product = that.data.modifyProducts[i];
        productModel.specsId = product.specsId;
        productModel.num = product.userOrderNum;
        submitProducts.push(productModel);
      }
      //console.log("submitProducts==",submitProducts);

      var item = JSON.stringify(submitProducts)

      api.request1({
        "specsList": item,
        "path": "user/updateUserSpecs",
        "tuangouId": that.data.tuangouID,
        "token": wx.getStorageSync('token')
      }, function (result) {

        if (result.code == '0') {
          that.hideModal()
          that.data.isModify = false;
          that.getTargetDetail(that.data.tuangouID);
        } else {
          wx.showModal({
            title: '提示',
            content: result.msg,
            showCancel: false,
            confirmText: '我知道了',
            complete: (res) => {
              if (res.cancel) {

              }

              if (res.confirm) {

              }
            }
          })
        }
      }, function (error) {})
    }
  },
  modifyOrder: function (e) {
    var that = this;
    var submitProducts = [];

    for (let i = 0; i < that.data.modifyProducts.length; ++i) {
      var productModel = {};
      var product = that.data.modifyProducts[i];
      productModel.specsId = product.specsId;
      productModel.num = product.userOrderNum;
      submitProducts.push(productModel);
    }
    //console.log("submitProducts==",submitProducts);
    var item = JSON.stringify(submitProducts)

    api.request1({
      "specsList": item,
      "path": "user/updateUserSpecs",
      "tuangouId": that.data.tuangouID,
      "token": wx.getStorageSync('token')
    }, function (result) {

      if (result.code == '0') {
        that.hideModal()
        that.data.isModify = false;
        that.getTargetDetail(that.data.tuangouID);
      } else {
        wx.showModal({
          title: '提示',
          content: result.msg,
          showCancel: false,
          confirmText: '我知道了',
          complete: (res) => {
            if (res.cancel) {

            }

            if (res.confirm) {

            }
          }
        })
      }
    }, function (error) {})
  },
  reachTakeOrder: function (e) {
    var that = this;

    // var num = 0;
    // for(let i=0;i<that.data.modifyProducts.length;++i){
    //   var pro = that.data.modifyProducts[i];
    //   if(pro.state ==2||pro.state ==3){
    //     num+=pro.userOrderNum;
    //   }
    // }

    // if(num>1){
    //   wx.showModal({
    //     title: '提示',
    //     content: '您共有 '+num+' 件商品要取货',
    //     cancelText:"否",
    //     confirmText:"是",
    //     complete: (res) => {
    //       if (res.cancel) {

    //       }

    //       if (res.confirm) {
    //         api.request1({ "path": "user/come","tuangouId":that.data.tuangouID,"token":wx.getStorageSync('token')}, function (result) {     
    //           if(result.code=='0'){
    //             that.getTargetDetail(that.data.tuangouID)
    //           }else if(result.code == '301'){
    //             that.getTargetDetail(that.data.tuangouID)
    //             wx.showModal({
    //               title: '提示',
    //               content: result.msg,
    //               showCancel:false,
    //               confirmText:'我知道了',
    //               complete: (res) => {

    //                 if (res.confirm) {

    //                 }
    //               }
    //             })
    //           }
    //         }, function (error) {
    //         })
    //       }
    //     }
    //   })
    //   return;
    // }

    api.request1({
      "path": "user/come",
      "tuangouId": that.data.tuangouID,
      "token": wx.getStorageSync('token')
    }, function (result) {
      if (result.code == '0') {
        wx.showModal({
          title: '提示',
          content: '您共有 ' + result.data.number + ' 件商品要取货',
          showCancel: false,
          confirmText: "我知道了",
          complete: (res) => {
            if (res.cancel) {}
            if (res.confirm) {}
          }
        })
        that.getTargetDetail(that.data.tuangouID)
      } else if (result.code == '301') {

        wx.showModal({
          title: '提示',
          content: result.msg,
          showCancel: false,
          confirmText: '我知道了',
          complete: (res) => {

            if (res.confirm) {
              that.getTargetDetail(that.data.tuangouID)
            }
          }
        })
      }
    }, function (error) {})
  },
  tomorrowAppoint: function (e) {
    var that = this;
    if (that.data.otherTuangou == 'true') {
      wx.navigateBack({
        delta: 1
      })
      return
    }

    getApp().globalData.isRelaunch = false
    api.request1({
      "path": "user/tuangouMore",
      "tuangouId": that.data.tuangouID,
      "token": wx.getStorageSync('token')
    }, function (result) {

      if (result.code == '0') {
        if (result.data.length > 0) {
          wx.navigateTo({
            url: '/pages/OtherTuangou/OtherTuangou?tuangouID=' + that.data.tuangouID,
          })
        }

      } else if (result.code == '301') {

        that.judgeAgreeKaituan();
      }
    }, function (error) {})

  },
  judgeAgreeKaituan: function () {
    var that = this
    let id = '582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs'
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        //console.log(res)
        if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关

          if (res.subscriptionsSetting.itemSettings) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState = res.subscriptionsSetting.itemSettings[id]; // 用户同意的消息模板id

            if (moIdState === 'accept') {
              //弹出自定义
              wx.showModal({
                title: '',
                content: '还未有其他团购上线，请关注小程序订阅消息息',
                showCancel: false,
                cancelText: '',
                confirmText: '我知道了',
                complete: (res) => {
                  if (res.cancel) {}

                  if (res.confirm) {
                    wx.requestSubscribeMessage({
                      tmplIds: ['582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs'],
                      success(res) {
                        var result = res["582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs"];
                        that.judgeUserRemind("582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs", "3", (result == 'accept' ? '1' : '0'))
                      },
                    })
                  }
                }
              })

            } else if (moIdState === 'reject') {
              wx.showModal({
                title: '',
                content: '您已拒绝接收订阅开团通知，可在设置里打开',
                showCancel: false,
                cancelText: '',
                confirmText: '我知道了',
                complete: (res) => {
                  if (res.cancel) {}

                  if (res.confirm) {}
                }
              })

            } else if (moIdState === 'ban') {
              //console.log("已被后台封禁");
            } else {
              wx.showModal({
                title: '',
                content: '还未有其他团购上线，请关注小程序订阅消息',
                showCancel: true,
                cancelText: '取消',
                confirmText: '订阅消息',
                complete: (res) => {
                  if (res.cancel) {}

                  if (res.confirm) {
                    wx.requestSubscribeMessage({
                      tmplIds: ['582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs'],
                      success(res) {
                        var result = res["582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs"];
                        that.judgeUserRemind("582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs", "3", (result == 'accept' ? '1' : '0'))
                      },
                    })
                  }
                }
              })
            }
          } else {
            wx.showModal({
              title: '',
              content: '还未有其他团购上线，请关注小程序订阅消息',
              showCancel: true,
              cancelText: '取消',
              confirmText: '订阅消息',
              complete: (res) => {
                if (res.cancel) {}

                if (res.confirm) {
                  wx.requestSubscribeMessage({
                    tmplIds: ['582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs'],
                    success(res) {
                      var result = res["582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs"];
                      that.judgeUserRemind("582-4Cq9kZL_ka822Yhgm-QnWljGvbFBf_QIklDYtbs", "3", (result == 'accept' ? '1' : '0'))
                    },
                  })
                }
              }
            })
          }
        } else {
          wx.openSetting({
            withSubscriptions: true,
          })
        }
      }
    })
  },
  handleRefresher(event) {
    // 发送请求获取最新的视频数据
    var that = this
    that.getTargetDetail(that.data.tuangouID);
  },
  startAnimation: function () {
    // 数组循环，每次开启动画弹出一个数组里面，完成动画之后重新排队
    let id = this.data.ballAnimationArray.pop();
    //console.log("id==",id);
    this.ballComponent[id].startAnimation(this.data.keyFrames);
  },

  // 小球组件动画结束
  endAnimation(e) {
    this.data.ballAnimationArray.unshift(e.detail);

    // 开启购物车动画
    // this.startShopCartAnimation();

  },

  // 创建购物车动画
  startShopCartAnimation() {
    // 动画没结束，不执行
    if (!this.data.finishShopCarAnimation) {
      return;
    }
    this.data.finishShopCarAnimation = false;
    this.animate(
      "#shopCart",
      [{
          scale: [0.8, 0.8],
        },
        {
          scale: [1.1, 1.1],
        },
        {
          scale: [0.9, 0.9],
        },
        {
          scale: [1, 1],
        },
      ],
      400,
      function () {
        this.data.finishShopCarAnimation = true;
      }.bind(this)
    );
  },
  scroll: function (res) {
    //console.log("ddd=",res)
    if (res.detail.scrollTop < 10) {
      this.setData({
        enablerefresh: true
      })
    } else {
      this.setData({
        enablerefresh: false
      })
    }
  },
  seeMoreOrder: function () {
    var that = this
    that.data.showModeOrder = true
    that.setData({
      showModeOrder: true,
      hideModal: !that.data.showTuanwuche,
      selectedProducts: that.data.modifyProducts,
      cancelNO: that.data.targetData.cancelNO,
      targetData: that.data.targetData,
      hasOrderedProduct: that.data.hasOrderedProduct,
    })
  },
  hideMoreOrder: function () {
    var that = this
    var newSelectProducts = []
    for (let i = 0; i < that.data.modifyProducts.length; i++) {
      var pro = that.data.modifyProducts[i];
      if (pro.isLastOrder != 1) {
        newSelectProducts.push(pro)
      }
    }
    that.data.showModeOrder = false
    that.setData({
      showModeOrder: false,
      hideModal: !that.data.showTuanwuche,
      selectedProducts: newSelectProducts,
      cancelNO: that.data.targetData.cancelNO,
      targetData: that.data.targetData,
      hasOrderedProduct: that.data.hasOrderedProduct,

    })
  },
  handlerGohomeClick() {
    console.log('ffff')
    //this.data.leaderID
    wx.navigateTo({
      url: '/pages/MineInfoPage/MineInfoPage?leaderId=' + 32
    });
  },
  judgeUserRemind: function (num, typeNum, yesNo) {
    var that = this
    let id = num
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        //console.log(res)
        if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
          if (res.subscriptionsSetting.itemSettings) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState = res.subscriptionsSetting.itemSettings[id]; // 用户同意的消息模板id
            if (moIdState === 'accept') {
              getApp().globalData.isCheck1 = 1
              //console.log('接受了消息推送');
              api.request1({
                "path": "user/remind",
                "tuangouId": that.data.tuangouID,
                "state": "1",
                "type": typeNum,
                "token": wx.getStorageSync('token')
              }, function (result) {
                if (result.code == '0') {}
              }, function (error) {})

            } else if (moIdState === 'reject') {
              //console.log('拒绝了消息推送');

            } else if (moIdState === 'ban') {
              //console.log("已被后台封禁");
            } else {
              api.request1({
                "path": "user/remind",
                "tuangouId": that.data.tuangouID,
                "state": "1",
                "type": typeNum,
                "token": wx.getStorageSync('token')
              }, function (result) {
                if (result.code == '0') {}
              }, function (error) {})
            }
          } else {
            api.request1({
              "path": "user/remind",
              "tuangouId": that.data.tuangouID,
              "state": "0",
              "type": typeNum,
              "token": wx.getStorageSync('token')
            }, function (result) {
              if (result.code == '0') {}
            }, function (error) {})
          }
        } else {
          wx.openSetting({
            withSubscriptions: true,
          })
        }
      }
    })
  },
})